<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* 小图 */
        /* https://img.alicdn.com/imgextra/i4/2231547606/O1CN01ynnAbG263b6VVxGqx_!!2231547606.jpg_430x430q90.jpg */
        /*大图 */
        /* https://img.alicdn.com/imgextra/i4/2231547606/O1CN01ynnAbG263b6VVxGqx_!!2231547606.jpg */
        body{
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
       #image{
           width: 300px;
           height: 300px;
           background-color: black;
           background-image: url('https://img.alicdn.com/imgextra/i4/2231547606/O1CN01ynnAbG263b6VVxGqx_!!2231547606.jpg');
           background-size:300px 300px ;
           background-repeat: no-repeat;
       } 
       #image[zoomed]{
           background-size: 900px 900px;
           background-position: calc(var(--x) * 100%) calc(var(--y) * 100%);
       }
    </style>
</head>
<body>

    <div id="image"></div>

    <script>
        function enterHandler(e){
            e.target.setAttribute('zoomed',1)
            moveHandler(e)
        }

        function moveHandler(e){
            // 获得容器的大小
            let rect = e.target.getBoundingClientRect()
            let offsetX,offsetY

            if(['touchstart','touchmove','touchend'].includes(e.type)){ //兼容移动端
                offsetX = e.touches[0].pageX - rect.left
                offsetY = e.touches[0].pageY - rect.top

                e.preventDefault() // 避免手指移动的时候触发页面的移动
            }else{
                offsetX = e.offsetX
                offsetY = e.offsetY
            }

            let x = offsetX / rect.width  //鼠标在图片容器上移动的X的像素值 / 容器的宽度 = 鼠标在容器里面移动的宽度的百分比
            let y = offsetY / rect.height  //鼠标在图片容器上移动的Y的像素值 / 容器的高度 = 鼠标在容器里面移动的高度的百分比

            e.target.style.setProperty('--x',x)
            e.target.style.setProperty('--y',y)
        }

        function leaveHandler(e){
            e.target.removeAttribute('zoomed')
            moveHandler(e)
        }

        document.querySelector('#image').addEventListener('mouseenter',enterHandler)
        document.querySelector('#image').addEventListener('mousemove',moveHandler)
        document.querySelector('#image').addEventListener('mouseleave',leaveHandler)


        //兼容手机版
        document.querySelector('#image').addEventListener('touchstart',enterHandler)
        document.querySelector('#image').addEventListener('touchmove',moveHandler)
        document.querySelector('#image').addEventListener('touchend',leaveHandler)
    </script>
</body>
</html>